package com.bnd.utils;

import cn.hutool.crypto.digest.BCrypt;

/**
 * 加解密与脱敏工具类
 */
public class EncryptUtils {

    /**
     * 使用 BCrypt 对密码进行加密
     *
     * @param rawPassword 明文密码
     * @return 加密后的哈希字符串
     */
    public static String encryptPassword(String rawPassword) {
        if (rawPassword == null || rawPassword.trim().isEmpty()) {
            throw new IllegalArgumentException("密码不能为空");
        }
        return BCrypt.hashpw(rawPassword, BCrypt.gensalt());
    }

    /**
     * 校验明文密码是否与加密后的哈希匹配
     *
     * @param rawPassword 明文密码
     * @param hashedPassword 已加密的密码（BCrypt 哈希）
     * @return 是否匹配
     */
    public static boolean matchesPassword(String rawPassword, String hashedPassword) {
        if (rawPassword == null || hashedPassword == null) {
            return false;
        }
        return BCrypt.checkpw(rawPassword, hashedPassword);
    }

    // ================== 2. 邮箱脱敏 ==================
    /**
     * 邮箱脱敏处理
     * 示例：zhangsan@example.com → z***@example.com
     *
     * @param email 邮箱地址
     * @return 脱敏后的邮箱
     */
    public static String maskEmail(String email) {
        if (email == null || email.isEmpty()) {
            return email;
        }

        if (!email.contains("@")) {
            return email;
        }

        String[] parts = email.split("@", 2);
        String local = parts[0];
        String domain = parts[1];

        if (local.isEmpty()) {
            return email;
        }

        String maskedLocal;
        if (local.length() == 1) {
            maskedLocal = local + "***";
        } else if (local.length() == 2) {
            maskedLocal = local.charAt(0) + "*";
        } else {
            maskedLocal = local.charAt(0) + "***";
        }

        return maskedLocal + "@" + domain;
    }
}